// 清理工具
import { useChatStore } from '@/store/chat.js'

/**
 * 清理空对话和无效数据
 */
export const cleanupEmptyChats = () => {
  console.log('=== 开始清理空对话 ===')
  
  try {
    const chatStore = useChatStore()
    
    if (!chatStore) {
      console.error('聊天store未初始化')
      return { success: false, error: '聊天store未初始化' }
    }
    
    // 清理空对话
    const removedCount = chatStore.cleanEmptyChats()
    
    console.log(`✅ 清理完成，删除了 ${removedCount} 个空对话`)
    
    // 显示当前有效对话数量
    const validChats = chatStore.chatHistory.filter(chat => 
      chat.messages && chat.messages.length > 0
    )
    
    console.log(`当前有效对话数量: ${validChats.length}`)
    
    return {
      success: true,
      removedCount,
      remainingCount: validChats.length
    }
    
  } catch (error) {
    console.error('❌ 清理失败:', error)
    return { success: false, error: error.message }
  }
}

/**
 * 温和清理（只在有空对话时清理）
 */
export const gentleCleanup = () => {
  console.log('=== 温和清理检查 ===')
  
  try {
    const chatStore = useChatStore()
    
    if (!chatStore) {
      console.error('聊天store未初始化')
      return { success: false, error: '聊天store未初始化' }
    }
    
    // 温和清理
    const removedCount = chatStore.removeEmptyChatsIfAny()
    
    if (removedCount > 0) {
      console.log(`✅ 温和清理完成，删除了 ${removedCount} 个空对话`)
    } else {
      console.log('✅ 没有发现空对话，无需清理')
    }
    
    return {
      success: true,
      removedCount,
      remainingCount: chatStore.chatHistory.length
    }
    
  } catch (error) {
    console.error('❌ 温和清理失败:', error)
    return { success: false, error: error.message }
  }
}

/**
 * 清理本地存储中的所有聊天数据
 */
export const clearAllChatData = () => {
  console.log('=== 开始清理所有聊天数据 ===')
  
  try {
    // 清理uni存储
    uni.removeStorageSync('chat_store_data')
    uni.removeStorageSync('qa_session_id')
    
    // 重置store状态
    const chatStore = useChatStore()
    if (chatStore) {
      chatStore.chatHistory = []
      chatStore.currentChatId = null
      chatStore.currentChat = null
      chatStore.lastSyncTime = null
    }
    
    console.log('✅ 所有聊天数据已清理')
    
    return { success: true }
    
  } catch (error) {
    console.error('❌ 清理失败:', error)
    return { success: false, error: error.message }
  }
}

/**
 * 获取存储统计信息
 */
export const getStorageStats = () => {
  console.log('=== 获取存储统计信息 ===')
  
  try {
    const chatStore = useChatStore()
    
    if (!chatStore) {
      return { success: false, error: '聊天store未初始化' }
    }
    
    const totalChats = chatStore.chatHistory.length
    const emptyChats = chatStore.chatHistory.filter(chat => 
      !chat.messages || chat.messages.length === 0
    ).length
    const validChats = totalChats - emptyChats
    
    const totalMessages = chatStore.chatHistory.reduce((sum, chat) => {
      return sum + (chat.messages ? chat.messages.length : 0)
    }, 0)
    
    const stats = {
      totalChats,
      validChats,
      emptyChats,
      totalMessages,
      currentChatId: chatStore.currentChatId,
      hasCurrentChat: !!chatStore.currentChat,
      lastSyncTime: chatStore.lastSyncTime
    }
    
    console.log('存储统计:', stats)
    
    return { success: true, stats }
    
  } catch (error) {
    console.error('❌ 获取统计失败:', error)
    return { success: false, error: error.message }
  }
}

/**
 * 在控制台注册清理命令
 */
export const registerCleanupCommands = () => {
  if (typeof window !== 'undefined' && window.console) {
    console.log('=== 清理工具 ===')
    console.log('运行以下命令进行清理:')
    console.log('- window.cleanupEmpty() // 清理所有空对话')
    console.log('- window.gentleCleanup() // 温和清理（只在有空对话时清理）')
    console.log('- window.forceSync() // 强制同步服务器数据')
    console.log('- window.clearAllChats() // 清理所有聊天数据')
    console.log('- window.getStats() // 获取存储统计')
    
    window.cleanupEmpty = cleanupEmptyChats
    window.gentleCleanup = gentleCleanup
    window.clearAllChats = clearAllChatData
    window.getStats = getStorageStats
    
    // 添加强制同步命令
    window.forceSync = async () => {
      try {
        const chatStore = useChatStore()
        if (chatStore && chatStore.syncFromServer) {
          console.log('🔄 开始强制同步...')
          await chatStore.syncFromServer()
          console.log('✅ 强制同步完成')
          getStorageStats() // 显示更新后的统计
        } else {
          console.error('❌ 无法同步：store未初始化或缺少同步方法')
        }
      } catch (error) {
        console.error('❌ 强制同步失败:', error)
      }
    }
    
    // 自动显示当前统计
    getStorageStats()
  }
} 